package com.it.you.base.stream;

import com.it.you.pojo.Child;
import com.it.you.pojo.Parent;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class StreamTest6 {
    public static void main(String[] args) {
        List<Parent> parents = new ArrayList<Parent>();
        Parent parent1 = new Parent();
        parent1.setName("parent1");
        Parent parent2 = new Parent();
        parent2.setName("parent2");
        Parent parent3 = new Parent();
        parent3.setName("parent3");
        Parent parent4 = new Parent();
        parent4.setName("parent4");

        Child child1 = new Child();
        child1.setName("child1");
        child1.setSex(1);
        parent1.setChild(child1);
        Child child2 = new Child();
        child2.setName("child2");
        child2.setSex(1);
        parent2.setChild(child2);
        Child child3 = new Child();
        child3.setName("child3");
        child3.setSex(2);
        parent3.setChild(child3);

        parents.add(parent1);
        parents.add(parent2);
        parents.add(parent3);
        parents.add(parent4);

        List<Parent> parentList = parents.stream().filter(parent -> parent.getName() != null)
                .filter(parent -> parent.getChild() != null).collect(Collectors.toList());
        System.out.println(parentList);

        long count = parents.stream().filter(parent -> parent.getName() != null)
                .filter(parent -> parent.getChild() != null).count();
        System.out.println(count);

        //找出有儿子的parent
        PredicateClass predicateClass = new PredicateClass();
        List<Parent> hasSonList1 = parents.stream().filter(predicateClass).collect(Collectors.toList());
        System.out.println(hasSonList1);

        //方法引用写法
        List<Parent> hasSonList2 = parents.stream().filter(Parent::hasSon).collect(Collectors.toList());
        System.out.println(hasSonList2);
        //匿名内部类写法 简化后就是 Parent::hasSon
        List<Parent> hasSonList3 = parents.stream().filter(new Predicate<Parent>() {
            @Override
            public boolean test(Parent parent) {
                return parent.hasSon();
            }
        }).collect(Collectors.toList());
        System.out.println(hasSonList3);

    }
}

class PredicateClass implements Predicate<Parent> {
    @Override
    public boolean test(Parent parent) {
        return parent.getChild() != null && parent.getChild().getSex() == 1;
    }
}
